/**
 * 微医讲堂入口
 * Created by alice on 2016/7/14.
 */
require.config({
    baseUrl:'../js',
    paths:{
        "getData":"Util/getData",
        "config":"common/config",
        "components":"common/components",
        "common":"common/common",
        "jquery":"lib/jquery.min",
        "weui":"lib/jquery-weui.min",
        "layout":"lib/layoutRem",
        "wx":"lib/jweixin-1.0.0"
    },
    shim : {
        "components": { deps : ["jquery"] },
        "weui":{deps:["jquery"]}
    },
    deps:['layout','jquery','weui'],
    urlArgs: "v=" + (new Date()).getTime()//以禁用浏览器缓存,上线后注释掉
});
require(['jquery','getData','config','common','components','weui','wx'],function($,getData,config,common,components,weui,wx){
    console.log(weui);
    var gm=common.gm;
    var _name=null;
    //tab index
    var itemIndex = 0;
    var token=gm.para.get(window.location.href,"token");
    $(".search").val("");
    //确定返回状态
    $(".conti div").removeClass("cjj");
    var status = window.location.hash;
    if(status == "#b"){
        $("div .playing").addClass("cjj");
        $(".ensss").siblings().hide();
        $(".ensss").show();
        $("#tab2").show();
        $("#tab1").hide();
        itemIndex=1;
    }else{
        $("div .all").addClass("cjj");
        $(".ensn").siblings().hide();
        $(".ensn").show();
        $("#tab1").show();
        $("#tab2").hide();
        itemIndex=0;
    }
    //下拉自动加载数据
    var generatedCount = 1;//页码
    $(document).ready(function (){
        var nScrollHight = 0; //滚动距离总长(注意不是滚动条的长度)
        var nScrollTop = 0;   //滚动到的当前位置
        var nDivHight = $("#wrapper").height()+$(".search_area").height();
        var isload=0;//防止多次加载
        $("#wrapper").scroll(function(){
            var that=this;
            nScrollHight = $(this)[0].scrollHeight;
            nScrollTop = $(this)[0].scrollTop;
            if(nScrollTop + nDivHight >= nScrollHight){
                if(itemIndex==0){
                    if(isload==0){
                        isload=1;
                        generatedCount++;
                        getData.getJson({
                            page:"doctor",
                            inter:"getDoctorCommonVideoList",
                            data:{"token":token,"pageSize":10,"videoHot":1,"pageNum":generatedCount},
                            method:"GET",
                            callback:function(data){
                                if(data.code=="2000"){
                                    if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                        loadEnd();
                                        isload=1;
                                    }else{
                                        var getstr=getstr=bindVideoList(data);
                                        $(".alllive ul.ensn").append(getstr.join(""));
                                        nScrollHight = $(that)[0].scrollHeight;
                                        nScrollTop = $(that)[0].scrollTop;
                                        nDivHight = $("#wrapper").height()+$(".search_area").height();
                                        if(nScrollTop+nDivHight<nScrollHight)
                                            isload=1;
                                    }
                                }

                            }
                        });

                    }
                }else if(itemIndex==1){
                    if(isload==0){
                        isload=1;
                        generatedCount++;
                         getData.getJson({
                         page:"doctor",
                         inter:"getDoctorCommonVideoList",
                         data:{"token":token,"pageSize":10,"pageNum":generatedCount},
                         method:"GET",
                         callback:function(data){
                         if(data.code=="2000"){
                         if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                         loadEnd1();
                         isload=1;
                         }else{
                         var getstr=getstr=bindVideoList(data);
                         $(".alllive ul.ensss").append(getstr.join(""));
                         nScrollHight = $(that)[0].scrollHeight;
                         nScrollTop = $(that)[0].scrollTop;
                         nDivHight = $("#wrapper").height()+$(".search_area").height();
                         if(nScrollTop+nDivHight<nScrollHight)
                         isload=1;
                         }
                    }

                }
     });

                    }
                }
            }else{//恢复加载更多
                isload=0;
            }

        });
    });

    function loadEnd1(){
        $(".pullUpLabel1").html("没有更多信息了！");
    }
    function loadEnd(){
        $(".pullUpLabel").html("没有更多信息了！");
    }
    /**
     * 初始化滚动加载
     */
    //infinite with navbar
    /*if($("#scroller")[0]){
        $("#tab1,#tab2").infinite(100).on("infinite", function() {
            var self = this;
            if(self.loading) return;
            self.loading = true;
            setTimeout(function() {
                if(itemIndex==0){
                    generatedCount++;
                    getData.getJson({
                        page:"doctor",
                        inter:"getDoctorCommonVideoList",
                        data:{"token":token,"pageSize":10,"videoHot":1,"pageNum":generatedCount},
                        method:"GET",
                        callback:function(data){
                            if(data.code=="2000"){
                                if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                    $("#tab1 #infinite_load_doctor").html("没有更多数据了！");
                                    $("#tab1").destroyInfinite();
                                }else{
                                    var getstr=getstr=bindVideoList(data);
                                    $(".alllive ul.ensn").append(getstr.join(""));

                                }
                            }

                        }
                    });
                }else if(itemIndex==1){
                    generatedCount++;
                    getData.getJson({
                        page:"doctor",
                        inter:"getDoctorCommonVideoList",
                        data:{"token":token,"pageSize":10,"pageNum":generatedCount},
                        method:"GET",
                        callback:function(data){
                            if(data.code=="2000"){
                                if(data.value!=undefined && data.value!=null && data.value.length==0){//无数据时
                                    $("#tab2 #infinite_load_doctor1").html("没有更多数据了！");
                                    $("#tab2").destroyInfinite();
                                }else{
                                    var getstr=getstr=bindVideoList(data);
                                    $(".alllive ul.ensss").append(getstr.join(""));
                                }
                            }

                        }
                    });
                }
                self.loading = false;
            }, 1000);   //模拟延迟
        });
    }*/



    $(".conti .all,.conti .playing").bind({
        touchend:function(){
            $(".conti div").removeClass("cjj");
            $(this).addClass("cjj");
            var $this = $(this);
            itemIndex = $this.index();
            var _p = $(this).index();

            if (_p == 0) {
                $(".ensn").siblings().hide();
                $(".ensn").show();
                window.location.hash = "#a";
                itemIndex=0;
                generatedCount=1;
                $("#tab1").show();
                $("#tab2").hide();
            }else{
                $(".ensss").siblings().hide();
                $(".ensss").show();
                window.location.hash = "#b";
                $("#tab2").show();
                $("#tab1").hide();
                itemIndex=1;
                generatedCount=1;
            }
            return false;
        }
    });

    //获取视频列表
    getData.getJson({
        page:"doctor",
        inter:"getDoctorCommonVideoList",
        data:{"token":token,"pageSize":10},
        method:"GET",
        callback:function(data){
            var getstr=bindVideoList(data);
            $(".alllive ul.ensss").append(getstr.join(""));
        }
    });



    //获取热门视频列表
    getData.getJson({
        page:"doctor",
        inter:"getDoctorCommonVideoList",
        data:{"token":token,"pageSize":10,"videoHot":1,"pageNum":1},
        method:"GET",
        callback:function(data){
            var getstr=getstr=bindVideoList(data);
            $(".alllive ul.ensn").append(getstr.join(""));
        }
    });
    //获取视频 的回调
    function bindVideoList(data){
        if(!data){
            components.alert("服务器出错!");
            return;
        }
        var arr=[];
        var tmp = '<li uuid="{uuid}" favid="{favoriteUuid}">\
            <a href="{url}">\
                <div class="asbg">\
                    <div class="live">\
                        <img src="{image}">\
                    </div>\
                    <div class="text">\
                        <div class="collectionContentTitle list_title">\
                        <p>{userName}-{videoName}</p>\
                        </div>\
                        <p class="time">\
                            {commentNumber}{collNumber}\
                        </p>\
                    </div>\
                </div>\
            </a>\
            </li>';
        $(data.value).each(function(i,o){
            o.image=gm.common.isObjUsable(o.image)?window._interfaceImgPath+""+o.image:window.___defaultImage;
            //是否收藏
            var isCollection=o["isCollect"] == 1?1:0;
            var title= o.videoName;//视频title
            var desc= o.videoIntroduction;//视频intr
            var img= "group1"+o.image.split('group1')[1];//图像
            var favoriteUuid=o.id;//视频id
            var contentType=1;

            var str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&favoriteUuid="+favoriteUuid+"&contentType="+contentType;

            o.url="playing.html?client=ios&token="+token+"&"+str;
            //o["sc"] = (o["sc"] == "1"?"redstars":"greystars");//redstars表示已经收藏 ，greystars表示 未收藏

            var commentNumber= o.commentNumber;
            if(!gm.common.isObjUsable(commentNumber))
                o.commentNumber="<span style='margin-right:.5rem;'>评论 0</span>";
            else
                o.commentNumber="<span style='margin-right:.5rem;'>评论 "+commentNumber+"</span>";
            var collNumber= o.collNumber;
            if(!gm.common.isObjUsable(collNumber))
                o.collNumber="<span style='margin-right:.5rem;'>收藏 0</span>";
            else
                o.collNumber="<span style='margin-right:.5rem;'>收藏 "+collNumber+"</span>";
            arr.push(gm.replace(tmp,o));
        });
        /*$(".alllive ul.ensss").html(arr.join(""));
        $(".alllive ul.ensn").html(arr1.join(""));*/
        //注册收藏
        return arr;
    }

    //获取焦点图
    getData.getJson({
        page:"doctor",
        inter:"getPlatformPic",
        data:{brandType:4,"token":token},
        callback:function(data){
            if(!data){
                components.alert("服务器出错!");
            }
            if(data.code=="2000"){
                //绑定视频列表
                var arr = [];
                var tmp = '<li>\
					<a href="{url}"><img src="{imageUrl}"></a>\
					<div class="des">\
						<p>{note}</p>\
					</div>\
				</li>';

                if (data.value.length > 0) {
                    $(data.value).each(function(i,o){
                        var dto=o.commonVideoDto;
                        o.imageUrl=gm.common.isObjUsable(o.imageUrl)?window._interfaceImgPath+""+o.imageUrl:window.___defaultImage;
                        //是否收藏
                        var isCollection=o["isCollect"] == 1?1:0;
                        var title= o.videoName;//视频title
                        var desc= o.videoIntroduction;//视频intr
                        var img=null;//图像
                        var favoriteUuid=o.id;//视频id
                        var contentType=1;
                        var str=null;
                        if(dto!=undefined && dto!=null){
                            isCollection=dto.isCollect==1?1:0;
                            title=dto.videoName?dto.videoName:"";
                            desc=dto.videoIntroduction?dto.videoIntroduction:title;
                            favoriteUuid=dto.id;
                            str="isCollection="+isCollection+"&title="+title+"&desc="+desc+"&img="+img+"&favoriteUuid="+favoriteUuid+"&contentType="+contentType;

                        }
                        if(o.url){
                            o.url =o.url+"&token="+token+"&"+str;
                        }else{
                            o.url=""
                        }
                        var des= o.note;
                        if(gm.common.isObjUsable(des)){//判断是否有文字描述信息
                            o.note=des;
                            $(".des").show();
                        }
                        arr.push(gm.replace(tmp,o));
                    });
                }

                $(".border .atlas").html(arr.join(""));
                focusbind();
            }else{
                components.alert(data.message);
            }
        }
    });
    //gm.lecture.getVideosByName();
    $(".search_area i").bind({
        touchend:function(){
            var _p = $(".search_area input").val();
            // gm.lecture.getVideosByName(_p);
            $(".playing").removeClass("cjj");
            $(".all").addClass("cjj");
            gm.pul.toUrl("search.html?client=ios&name="+_p+"&token="+token);
        }
    });


    function focusbind(){
        //对象&变量 缓存
        var $tab = $("#tabs .border"),
            $ul = $tab.find("ul"),
            $li = $ul.children(),
            $nav = $("<nav>"),
            li_len = $li.length,
            li_w = $li.eq(0).width();console.log(li_w);

        //容器 初始化
        $li.css({
                "float" : "left",
                "width" : li_w
            })
            .each(function(i){
                var str = i == 0 ? "<i class=\"cur\">" : "<i>";
                $nav.append(str);
            });
        $nav.appendTo($tab);
        $li.eq(0).clone().appendTo($ul);
        $li.eq(-1).clone().css("marginLeft",-li_w).prependTo($ul);
        $ul.css("float","left").width(li_w * $ul.children().length);

        //切换 方法
        var eventOff,startX,clientX,
            index = 0,
            eventMaxWidth = li_w,
            objStatus = {},
            eventTo,
            time=5000,
            tab = {
                //开始
                start : function (event){
                    //重置水平位置
                    clientX = 0;
                    //滑动激活
                    eventOff = true;
                    //获取鼠标||触点水平坐标
                    var touch = event.touches && event.touches[0] || event;
                    //记录初始坐标
                    startX = touch.clientX;
                    //记录切换前对象状态
                    objStatus.left = $ul.get(0).style.marginLeft;
                    //阻止对象默认行为
                    // event.preventDefault();
                    console.log("准备切换");
                    clearInterval(eventTo);
                },
                //移动
                move : function (event){
                    var touch = event.touches && event.touches[0] || event,
                        _x = touch.clientX - startX;
                    if(eventOff){
                        clientX = parseInt(_x/eventMaxWidth * 100);
                        $ul.get(0).style.marginLeft = (li_w * clientX / 100) - li_w * index + "px";
                        //console.log("滑动进度：" + clientX + "%");
                    }
                    event.preventDefault();
                    // event.preventDefault();
                },
                //结束
                end : function (event){
                    var _clientX = clientX > 0 ? clientX : -(clientX);
                    //滑动激活，且滑动百分比超过50
                    if(eventOff){
                        if(_clientX >= 30){
                            index = clientX > 0 ? index - 1 : index + 1;
                            tab.to();
                            console.log("切换完成");
                        }
                        else{
                            console.log("放弃切换");

                            $ul.animate({
                                "marginLeft" : objStatus.left
                            });
                        }

                        eventOff = false;
                    }
                    eventTo = setInterval(function(){
                        index++;
                        tab.to();
                    },time);
                    // event.preventDefault();
                },
                to:function(){
                    var moveCallback;
                    objStatus.left = -(li_w * index) + "px";
                    //复位
                    if(index >= li_len){
                        index = 0;
                        moveCallback = function(){
                            $ul.get(0).style.marginLeft = -(li_w * index) + "px";
                        };
                    }
                    else if(index < 0){
                        index = li_len - 1;
                        moveCallback = function(){
                            $ul.get(0).style.marginLeft = -(li_w * index) + "px";
                        };
                    }
                    $nav.children().eq(index).addClass("cur").siblings().removeClass("cur");
                    $ul.animate({
                        "marginLeft" : objStatus.left
                    },moveCallback);
                }
            };



        eventTo = setInterval(function(){
            index++;
            tab.to();
        },time);
        //防止表单提交
        $('form').on('submit', function(e){
            // 不提交
            return false;
        });
        //触摸事件 注册
        $tab.get(0).addEventListener("touchstart",tab.start,false);
        $tab.get(0).addEventListener("touchmove",tab.move,false);
        $tab.get(0).addEventListener("touchend",tab.end,false);
    }

});